package com.pactera.madp.cp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.cp.api.bo.FromUserInfoBO;
import com.pactera.madp.cp.api.bo.IndexMsgBO;
import com.pactera.madp.cp.api.dto.ReqToUsersDTO;
import com.pactera.madp.cp.api.dto.wm.ReqMsgIndexDTO;
import com.pactera.madp.cp.api.em.workmessage.MsgEnum;
import com.pactera.madp.cp.api.entity.WorkContactEntity;
import com.pactera.madp.cp.api.entity.WorkEmployeeEntity;
import com.pactera.madp.cp.api.entity.WorkRoomEntity;
import com.pactera.madp.cp.api.entity.wm.WorkMsgEntity;
import com.pactera.madp.cp.api.feign.RemoteDeptService;
import com.pactera.madp.cp.api.vo.contact.ContactVO;
import com.pactera.madp.cp.common.util.DateUtils;
import com.pactera.madp.cp.common.util.PageUtil;
import com.pactera.madp.cp.common.util.wm.WorkMsgHelper;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.job.WorkMsgBackUpUtil;
import com.pactera.madp.cp.mapper.ContactMapper;
import com.pactera.madp.cp.mapper.WorkContactRoomMapper;
import com.pactera.madp.cp.mapper.WorkEmployeeMapper;
import com.pactera.madp.cp.mapper.wm.WorkMsgIndexMapper;
import com.pactera.madp.cp.mapper.wm.WorkMsgMapper;
import com.pactera.madp.cp.mapper.workroom.WorkRoomMapper;
import com.pactera.madp.cp.service.IChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: yangpengwei
 * @time: 2020/11/25 5:45 下午
 * @description 运营-聊天记录业务实现
 */
@Service
@Slf4j
public class ChatServiceImpl implements IChatService {

    @Autowired
    private WorkEmployeeMapper workEmployeeMapper;
    @Autowired
    private ContactMapper workContactMapper;
    @Autowired
    private WorkRoomMapper workRoomMapper;
    @Autowired
    private WorkContactRoomMapper workContactRoomMapper;
    @Autowired
    private WorkMsgIndexMapper workMsgIndexMapper;
    @Autowired
    private RemoteDeptService remoteDeptService;
    @Autowired
    private WorkMsgMapper workMsgMapper;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 会话内容存档 - 会话员工下拉
     * 获取对应公司员工简略信息
     *
     * @param name 员工名
     * @return 员工信息集合
     */
    @Override
    public Page<FromUserInfoBO> getFromUserInfoList(String name, Integer type, Integer deptId, Page page) {
        int corpId = CorpContextHolder.getCorpId();
        switch (type) {
            case 0:
                List<String> deptIds = remoteDeptService.getUserNameByDeptId(deptId);
                QueryWrapper<WorkEmployeeEntity> wrapper = new QueryWrapper<>();
                wrapper.select("id", "name", "avatar", "gender");
                wrapper.eq("corp_id", corpId);
                if (null != name && !name.isEmpty()) {
                    wrapper.like("name", name);
                }
                wrapper.in("wx_user_id", deptIds);
                page = (Page) workEmployeeMapper.selectPage(page, wrapper);
                List<FromUserInfoBO> fromUsers = new ArrayList<>();
                List<WorkEmployeeEntity> list = page.getRecords();
                for (WorkEmployeeEntity e : list) {
                    FromUserInfoBO fromUserInfoBO = new FromUserInfoBO();
                    fromUserInfoBO.setId(e.getId());
                    fromUserInfoBO.setName(e.getName());
                    fromUserInfoBO.setAvatar(e.getAvatar());
                    fromUserInfoBO.setGender(e.getGender());
                    fromUsers.add(fromUserInfoBO);
                }
                page.setRecords(fromUsers);
                return page;
            case 1:
                QueryWrapper<WorkContactEntity> contactWrapper = new QueryWrapper<>();
                contactWrapper.select("id", "name", "avatar", "gender");
                contactWrapper.eq("corp_id", corpId);
                if (null != name && !name.isEmpty()) {
                    contactWrapper.like("name", name);
                }
                List<FromUserInfoBO> fromUser = new ArrayList<>();
                page = (Page) workContactMapper.selectPage(page, contactWrapper);
                List<WorkContactEntity> records = page.getRecords();

                for (WorkContactEntity e : records) {
                    FromUserInfoBO fromUserInfoBO = new FromUserInfoBO();
                    fromUserInfoBO.setId(e.getId());
                    fromUserInfoBO.setName(e.getName());
                    fromUserInfoBO.setAvatar(e.getAvatar());
                    fromUserInfoBO.setGender(e.getGender());
                    fromUser.add(fromUserInfoBO);
                }

                page.setRecords(fromUser);
                return page;
            default:
                return page;
        }
    }

    @Override
    public Page<FromUserInfoBO> getFromUserInfoListByContact(String name, Page page) {
        int corpId = CorpContextHolder.getCorpId();
        QueryWrapper<WorkContactEntity> contactWrapper = new QueryWrapper<>();
        contactWrapper.select("id", "name", "avatar", "gender");
        contactWrapper.eq("corp_id", corpId);
        if (null != name && !name.isEmpty()) {
            contactWrapper.like("name", name);
        }
        List<FromUserInfoBO> fromUser = new ArrayList<>();
        page = (Page) workContactMapper.selectPage(page, contactWrapper);
        List<WorkContactEntity> records = page.getRecords();

        for (WorkContactEntity e : records) {
            FromUserInfoBO fromUserInfoBO = new FromUserInfoBO();
            fromUserInfoBO.setId(e.getId());
            fromUserInfoBO.setName(e.getName());
            fromUserInfoBO.setAvatar(e.getAvatar());
            fromUserInfoBO.setGender(e.getGender());
            fromUser.add(fromUserInfoBO);
        }

        page.setRecords(fromUser);
        return page;
    }

    @Override
    public List<FromUserInfoBO> getFromUserInfoList(String name, Integer deptId) {
        int corpId = CorpContextHolder.getCorpId();
        List<String> deptIds = remoteDeptService.getUserNameByDeptId(deptId);
        if (deptIds.isEmpty()) {
            return new LinkedList<>();

        }
        QueryWrapper<WorkEmployeeEntity> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name", "avatar", "gender");
        wrapper.eq("corp_id", corpId);
        if (null != name && !name.isEmpty()) {
            wrapper.like("name", name);
        }
        wrapper.in("wx_user_id", deptIds);

        List<FromUserInfoBO> fromUsers = new ArrayList<>();
        List<WorkEmployeeEntity> list = workEmployeeMapper.selectList(wrapper);
        for (WorkEmployeeEntity e : list) {
            FromUserInfoBO fromUserInfoBO = new FromUserInfoBO();
            fromUserInfoBO.setId(e.getId());
            fromUserInfoBO.setName(e.getName());
            fromUserInfoBO.setAvatar(e.getAvatar());
            fromUserInfoBO.setGender(e.getGender());
            fromUsers.add(fromUserInfoBO);
        }
        return fromUsers;
    }

    /**
     * 会话内容存档 - 会话对象列表(员工)
     *
     * @return 会话对象信息集合
     */
    @Override
    public R getToUserInfoList(ReqToUsersDTO req, Page page) {
        int toUserType = req.getUsertype();
        int corpId = CorpContextHolder.getCorpId();
        WorkEmployeeEntity employeeOneEntity = workEmployeeMapper.selectOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                .eq(WorkEmployeeEntity::getId, req.getUserId())
                .eq(WorkEmployeeEntity::getCorpId, corpId));
        if (null == employeeOneEntity) {
            throw new CheckedException("员工id 无效");
        }
        Map<String, Object> sqlMap = new HashMap<>(5);
        sqlMap.put("wxUserId", employeeOneEntity.getWxUserId());
        sqlMap.put("toListType", toUserType);
        sqlMap.put("userName", req.getName());
        sqlMap.put("corpId", corpId);
        List<String> userList = workMsgMapper.selectContactByUser(sqlMap);
        if (userList.size() > 0) {
            switch (toUserType) {
                case 0:
                    ArrayList<ContactVO> contactVOS = new ArrayList<>();
                    for (int i = 0; i < userList.size(); i++) {
                        String userId = JSONArray.parseArray(userList.get(i), String.class).get(0);
                        WorkEmployeeEntity entity = workEmployeeMapper.selectOne(Wrappers.<WorkEmployeeEntity>lambdaQuery().eq(WorkEmployeeEntity::getWxUserId, userId).eq(WorkEmployeeEntity::getCorpId, corpId));
                        if (null == entity) {
                            continue;
                        }
                        ContactVO contactVO = new ContactVO();
                        BeanUtil.copyProperties(entity, contactVO);
                        contactVOS.add(contactVO);
                    }
                    return R.ok(PageUtil.split(contactVOS, Integer.valueOf(String.valueOf(page.getCurrent())), Integer.valueOf(String.valueOf(page.getSize()))));
                case 1:
                    ArrayList<ContactVO> emVOS = new ArrayList<>();
                    for (int i = 0; i < userList.size(); i++) {
                        String userId = JSONArray.parseArray(userList.get(i), String.class).get(0);
                        WorkContactEntity entity = workContactMapper.selectOne(Wrappers.<WorkContactEntity>lambdaQuery().eq(WorkContactEntity::getWxExternalUserid, userId).eq(WorkContactEntity::getCorpId, corpId));
                        if (null == entity) {
                            continue;
                        }
                        ContactVO contactVO = new ContactVO();
                        BeanUtil.copyProperties(entity, contactVO);
                        emVOS.add(contactVO);
                    }
                    return R.ok(PageUtil.split(emVOS, Integer.valueOf(String.valueOf(page.getCurrent())), Integer.valueOf(String.valueOf(page.getSize()))));
                case 2:
                    ArrayList<ContactVO> roomVOS = new ArrayList<>();
                    for (int i = 0; i < userList.size(); i++) {
                        String userId = userList.get(i);
                        WorkRoomEntity entity = workRoomMapper.selectOne(Wrappers.<WorkRoomEntity>lambdaQuery().eq(WorkRoomEntity::getWxChatId, userId).eq(WorkRoomEntity::getCorpId, corpId));
                        if (null == entity) {
                            continue;
                        }
                        ContactVO contactVO = new ContactVO();
                        BeanUtil.copyProperties(entity, contactVO);
                        roomVOS.add(contactVO);
                    }
                    return R.ok(PageUtil.split(roomVOS, Integer.valueOf(String.valueOf(page.getCurrent())), Integer.valueOf(String.valueOf(page.getSize()))));
                default:
                    throw new CheckedException("类型输入错误");
            }
        } else {
            return R.ok(page);
        }
    }

    @Override
    public R getToContactInfoList(ReqToUsersDTO req, Page page) {
        int toUserType = req.getUsertype();
        int corpId = CorpContextHolder.getCorpId();
        WorkContactEntity contactEntity = workContactMapper.selectOne(Wrappers.<WorkContactEntity>lambdaQuery()
                .eq(WorkContactEntity::getId, req.getUserId())
                .eq(WorkContactEntity::getCorpId, corpId));
        if (null == contactEntity) {
            throw new CheckedException("客户id 无效");
        }
        Map<String, Object> sqlMap = new HashMap<>(5);
        sqlMap.put("corpId", corpId);
        sqlMap.put("wxUserId", contactEntity.getWxExternalUserid());
        if (StringUtils.isNotEmpty(req.getName())) {
            WorkEmployeeEntity employeeOneEntity = workEmployeeMapper.selectOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                    .eq(WorkEmployeeEntity::getName, req.getName())
                    .eq(WorkEmployeeEntity::getCorpId, corpId));
            if (ObjectUtil.isNotNull(employeeOneEntity)) {
                sqlMap.put("userName", employeeOneEntity.getWxUserId());
            }
        }
        if (toUserType == 0) {
            sqlMap.put("toListType", toUserType);
        } else if (toUserType == 2) {
            sqlMap.put("toListType", toUserType);
        }
        List<String> userList = workMsgMapper.selectContactByUser(sqlMap);
        if (userList.size() > 0) {
            switch (toUserType) {
                case 0:
                    ArrayList<ContactVO> contactVOS = new ArrayList<>();
                    for (int i = 0; i < userList.size(); i++) {
                        String userId = JSONArray.parseArray(userList.get(i), String.class).get(0);
                        WorkEmployeeEntity entity = workEmployeeMapper.selectOne(Wrappers.<WorkEmployeeEntity>lambdaQuery().eq(WorkEmployeeEntity::getWxUserId, userId).eq(WorkEmployeeEntity::getCorpId, corpId));
                        if (null == entity) {
                            continue;
                        }
                        ContactVO contactVO = new ContactVO();
                        BeanUtil.copyProperties(entity, contactVO);
                        contactVOS.add(contactVO);
                    }
                    return R.ok(PageUtil.split(contactVOS, Integer.valueOf(String.valueOf(page.getCurrent())), Integer.valueOf(String.valueOf(page.getSize()))));
                case 2:
                    ArrayList<ContactVO> roomVOS = new ArrayList<>();
                    for (int i = 0; i < userList.size(); i++) {
                        String userId = userList.get(i);
                        WorkRoomEntity entity = workRoomMapper.selectOne(Wrappers.<WorkRoomEntity>lambdaQuery().eq(WorkRoomEntity::getWxChatId, userId).eq(WorkRoomEntity::getCorpId, corpId));
                        if (null == entity) {
                            continue;
                        }
                        ContactVO contactVO = new ContactVO();
                        BeanUtil.copyProperties(entity, contactVO);
                        roomVOS.add(contactVO);
                    }
                    return R.ok(PageUtil.split(roomVOS, Integer.valueOf(String.valueOf(page.getCurrent())), Integer.valueOf(String.valueOf(page.getSize()))));
                default:
                    throw new CheckedException("类型输入错误");
            }
        } else {
            return R.ok(page);
        }
    }

    /**
     * 会话内容存档 - 列表
     *
     * @return 聊天记录集合
     */
    @Override
    public R index(ReqMsgIndexDTO req, Page page) {
        int corpId = CorpContextHolder.getCorpId();
        List<IndexMsgBO> respList = new ArrayList<>();
        int total = 0;
        Integer userType = req.getUserType();
        if (userType == null) return getContactList(req, page);
        switch (userType) {
            case 0:
                return getEmployeeList(req, page);
            case 1:
                return getContactList(req, page);
            default:
                return R.ok(page);
        }
    }

    @Override
    public R<Page<IndexMsgBO>> indexPage(ReqMsgIndexDTO req, Page page) {
        Integer corpId = CorpContextHolder.getCorpId();
        ArrayList<IndexMsgBO> indexMsgBOS = new ArrayList<>();
        Map<String, Object> selectParamMap = new HashMap<>(9);
        List<WorkMsgEntity> workMsgEntities = null;
        selectParamMap.put("corpId", corpId);
        selectParamMap.put("msgType", req.getType());
        selectParamMap.put("content", req.getContent());
        if (StringUtils.isNotEmpty(req.getDateTimeEnd()) && StringUtils.isNotEmpty(req.getDateTimeStart())) {
            try {
                selectParamMap.put("dateTimeStart", simpleDateFormat.parse(req.getDateTimeStart() + " 00:00:00").getTime());
                selectParamMap.put("dateTimeEnd", simpleDateFormat.parse(req.getDateTimeEnd() + " 23:59:59").getTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotEmpty(req.getUserName()) && StringUtils.isEmpty(req.getToUserName())) {
            WorkEmployeeEntity employeeEntity = workEmployeeMapper.selectOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                    .select(WorkEmployeeEntity::getWxUserId)
                    .eq(WorkEmployeeEntity::getName, req.getUserName())
                    .eq(WorkEmployeeEntity::getCorpId, corpId));
            if (null == employeeEntity) {
                return R.ok(page);
            }
            selectParamMap.put("from", employeeEntity.getWxUserId());
            workMsgEntities = workMsgMapper.findUser(selectParamMap);
        } else if (StringUtils.isNotEmpty(req.getUserName()) && StringUtils.isNotEmpty(req.getToUserName())) {
            WorkEmployeeEntity employeeEntity = workEmployeeMapper.selectOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                    .select(WorkEmployeeEntity::getWxUserId)
                    .eq(WorkEmployeeEntity::getName, req.getUserName())
                    .eq(WorkEmployeeEntity::getCorpId, corpId));
            if (null == employeeEntity) {
                return R.ok(page);
            }
            WorkContactEntity contactEntity = workContactMapper.selectOne(Wrappers.<WorkContactEntity>lambdaQuery()
                    .select(WorkContactEntity::getWxExternalUserid)
                    .eq(WorkContactEntity::getNickName, req.getToUserName())
                    .eq(WorkContactEntity::getCorpId, corpId));
            if (null == contactEntity) {
                return R.ok(page);
            }
            selectParamMap.put("from", employeeEntity.getWxUserId());
            selectParamMap.put("to", contactEntity.getWxExternalUserid());
            selectParamMap.put("toUserType", req.getToUserType());
            workMsgEntities = workMsgMapper.findUserAndContact(selectParamMap);
        } else if (StringUtils.isEmpty(req.getUserName()) && StringUtils.isNotEmpty(req.getToUserName())) {
            WorkContactEntity contactEntity = workContactMapper.selectOne(Wrappers.<WorkContactEntity>lambdaQuery()
                    .select(WorkContactEntity::getWxExternalUserid)
                    .eq(WorkContactEntity::getNickName, req.getToUserName())
                    .eq(WorkContactEntity::getCorpId, corpId));
            if (null == contactEntity) {
                return R.ok(page);
            }
            selectParamMap.put("from", contactEntity.getWxExternalUserid());
            workMsgEntities = workMsgMapper.findContact(selectParamMap);
        } else {
            workMsgEntities = workMsgMapper.findAll(selectParamMap);
        }

        workMsgEntities.forEach(workMsgEntity -> {
            if (StringUtils.isEmpty(workMsgEntity.getFrom())) {
                return;
            }
            String name = null;
            String avatar = null;
            if (req.getToUserId() != null && req.getUserId() != null) {
                WorkEmployeeEntity tempResultEmployee = getEmployeeInfo(req.getUserId());
                WorkContactEntity tempResultContact = getContactInfo(req.getToUserId());
                name = workMsgEntity.getTolistType() == 1 ? tempResultEmployee.getName() : tempResultContact.getName();
                avatar = workMsgEntity.getTolistType() == 1 ? tempResultEmployee.getAvatar() : tempResultContact.getName();
            } else if (req.getUserId() != null && req.getToUserId() == null) {
                WorkEmployeeEntity tempResultEmployee = getEmployeeInfo(req.getUserId());
                name = tempResultEmployee.getName();
                avatar = tempResultEmployee.getAvatar();
            } else if (req.getUserId() == null && req.getToUserId() != null) {
                WorkContactEntity tempResultContact = getContactInfo(req.getToUserId());
                name = tempResultContact.getName();
                avatar = tempResultContact.getAvatar();
            } else {
                WorkEmployeeEntity tempResultEmployee = workEmployeeMapper.selectOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                        .eq(WorkEmployeeEntity::getWxUserId, workMsgEntity.getFrom())
                        .eq(WorkEmployeeEntity::getCorpId, corpId));
                if (null == tempResultEmployee) {
                    WorkContactEntity tempResultContact = workContactMapper.selectOne(Wrappers.<WorkContactEntity>lambdaQuery()
                            .eq(WorkContactEntity::getWxExternalUserid, workMsgEntity.getFrom())
                            .eq(WorkContactEntity::getCorpId, corpId));
                    if (ObjectUtil.isNotNull(tempResultContact)) {
                        name = tempResultContact.getName();
                        avatar = tempResultContact.getAvatar();
                    }
                } else {
                    name = tempResultEmployee.getName();
                    avatar = tempResultEmployee.getAvatar();
                }
            }
            IndexMsgBO indexMsgBO = new IndexMsgBO();
            indexMsgBO.setAvatar(avatar);
            indexMsgBO.setName(name);
            indexMsgBO.setToListType(workMsgEntity.getTolistType());
            indexMsgBO.setAction(MsgEnum.getEnum(workMsgEntity.getAction()));
            indexMsgBO.setContent(JSONObject.parseObject(workMsgEntity.getContent()));
            String msgTime = workMsgEntity.getMsgTime();
            indexMsgBO.setMsgDataTime(DateUtils.formatS1(msgTime));
            indexMsgBOS.add(indexMsgBO);
        });
        if (workMsgEntities == null) {
            return R.ok(page);
        }
        return R.ok(PageUtil.split(indexMsgBOS, (int) page.getCurrent(), (int) page.getSize()));
    }

    @Override
    public void exitExcelList(ReqMsgIndexDTO req, HttpServletResponse response, OutputStream out) throws IOException {
        Page<List<IndexMsgBO>> listPage = new Page<List<IndexMsgBO>>();
        listPage.setCurrent(req.getCurrent());
        listPage.setSize(req.getSize());
        R<Page<IndexMsgBO>> pageR = indexPage(req, listPage);
        List<IndexMsgBO> records = pageR.getData().getRecords();
        //把要导出到excel的数据的LinkedHashMap装载到这个List里面,这是导出工具类要求封装格式.
        List<Map<String, Object>> exportData = new ArrayList<>();
        records.forEach(indexMsgBO -> {
            LinkedHashMap<String, Object> reportData = new LinkedHashMap<>();
            //装载数据,就是要导出到excel的数据
            reportData.put("发送者", indexMsgBO.getName());
            reportData.put("内容", indexMsgBO.getContent().get("content"));
            reportData.put("发送状态", indexMsgBO.getAction());
            reportData.put("发送时间", indexMsgBO.getMsgDataTime());
            exportData.add(reportData);
        });
        log.info("聊天记录开始导出 = " + exportData);
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(exportData, true);
        //out为OutputStream，需要写出到的目标流
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=liaotian.xls");
        out = response.getOutputStream();
        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }

    /**
     * 获取客户信息
     *
     * @param id
     * @return
     */
    private WorkContactEntity getContactInfo(Integer id) {
        Integer corpId = CorpContextHolder.getCorpId();
        return workContactMapper.selectOne(Wrappers.<WorkContactEntity>lambdaQuery()
                .eq(WorkContactEntity::getId, id)
                .eq(WorkContactEntity::getCorpId, corpId));
    }

    /**
     * 获取用户信息
     *
     * @param id
     * @return
     */
    private WorkEmployeeEntity getEmployeeInfo(Integer id) {
        Integer corpId = CorpContextHolder.getCorpId();
        return workEmployeeMapper.selectOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                .eq(WorkEmployeeEntity::getId, id)
                .eq(WorkEmployeeEntity::getCorpId, corpId));
    }

    public R getEmployeeList(ReqMsgIndexDTO req, Page page) {
        int corpId = CorpContextHolder.getCorpId();
        List<IndexMsgBO> respList = new ArrayList<>();
        int total = 0;
        Integer userType = req.getUserType();
        WorkEmployeeEntity fromEmployee = workEmployeeMapper.selectById(req.getUserId());
        if (null == fromEmployee) {
            return R.ok(page);
        }
        String fromWxId = fromEmployee.getWxUserId();
        String fromName = fromEmployee.getName();
        String fromAvatar = fromEmployee.getAvatar();

        String toWxId = "";
        int toUserType = req.getToUserType();
        if (toUserType == 0) {
            // 通讯录
            WorkEmployeeEntity toEmployee = workEmployeeMapper.selectById(req.getToUserId());
            if (null == toEmployee) {
                throw new CheckedException("检索对象id 无效");
            }
            toWxId = toEmployee.getWxUserId();
        }
        if (toUserType == 1) {
            // 外部联系人
            WorkContactEntity toContact = workContactMapper.selectById(req.getToUserId());
            if (null == toContact) {
                throw new CheckedException("检索对象id 无效");
            }
            toWxId = toContact.getWxExternalUserid();
        }
        if (toUserType == 2) {
            // 群聊
            WorkRoomEntity roomEntity = workRoomMapper.selectById(req.getToUserId());
            if (null == roomEntity) {
                throw new CheckedException("检索对象id 无效");
            }
            toWxId = roomEntity.getWxChatId();
        }
        // 设置检索条件
        Map<String, Object> selectParamMap = new HashMap<>(9);
        //selectParamMap.put("corpId", corpId);
        selectParamMap.put("from", fromWxId);
        selectParamMap.put("msgType", req.getType());
        selectParamMap.put("to", toWxId);
        selectParamMap.put("toUserType", toUserType);
        selectParamMap.put("content", req.getContent());
        if (StringUtils.isNotEmpty(req.getDateTimeEnd()) && StringUtils.isNotEmpty(req.getDateTimeStart())) {
            try {
                selectParamMap.put("dateTimeStart", simpleDateFormat.parse(req.getDateTimeStart() + " 00:00:00").getTime());
                selectParamMap.put("dateTimeEnd", simpleDateFormat.parse(req.getDateTimeEnd() + " 23:59:59").getTime());
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        selectParamMap.put("lastIndex", page.getCurrent() * page.getSize() - 1);
        selectParamMap.put("size", page.getSize());

        List<WorkMsgEntity> resultList = workMsgMapper.selectToUserMsg(selectParamMap);
        total = workMsgMapper.selectToUserMsgCount(selectParamMap);


        WorkEmployeeEntity tempEmployee = new WorkEmployeeEntity();
        WorkContactEntity tempContact = new WorkContactEntity();

        Map<String,Object> cacheMap = new HashMap<>();
        for (int i = 0; i < resultList.size(); i++) {
            WorkMsgEntity result = resultList.get(i);
            IndexMsgBO indexMsgBO = new IndexMsgBO();

            String resultFromWxId = result.getFrom();
            int isCurrentUser = fromWxId.equals(resultFromWxId) ? 1 : 0;

            indexMsgBO.setIsCurrentUser(isCurrentUser);
            indexMsgBO.setAction(MsgEnum.getEnum(result.getAction()));
            indexMsgBO.setToListType(result.getTolistType());

            int typeCode = result.getMsgType();
            typeCode = typeCode > 14 ? 100 : typeCode;

            indexMsgBO.setType(typeCode);
            indexMsgBO.setContent(JSON.parseObject(result.getContent()));

            String msgTime = result.getMsgTime();
            indexMsgBO.setMsgDataTime(DateUtils.formatS1(msgTime));

            String resultFromName;
            String resultFromAvatar;
            if (isCurrentUser == 1) {
                resultFromName = fromName;
                resultFromAvatar = fromAvatar;
            } else {
                if (WorkMsgBackUpUtil.isContact(resultFromWxId)) {
                    tempContact.setWxExternalUserid(resultFromWxId);
                    WorkContactEntity tempResultContact;
                    if (cacheMap.get(resultFromWxId) != null) {
                        tempResultContact = (WorkContactEntity) cacheMap.get(resultFromWxId);
                    } else {
                        tempResultContact = workContactMapper.selectOne(Wrappers.<WorkContactEntity>lambdaQuery()
                                .eq(WorkContactEntity::getWxExternalUserid, resultFromWxId));
                        cacheMap.put(resultFromWxId, tempResultContact);
                    }
                    resultFromName = tempResultContact.getName();
                    resultFromAvatar = tempResultContact.getAvatar();
                } else {
                    tempEmployee.setWxUserId(resultFromWxId);
                    WorkEmployeeEntity tempResultEmployee;
                    if (cacheMap.get(resultFromWxId) != null) {
                        tempResultEmployee = (WorkEmployeeEntity) cacheMap.get(resultFromWxId);
                    } else {
                        tempResultEmployee = workEmployeeMapper.selectOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                                .eq(WorkEmployeeEntity::getWxUserId, resultFromWxId));
                        cacheMap.put(resultFromWxId, tempResultEmployee);
                    }
                    resultFromName = tempResultEmployee.getName();
                    resultFromAvatar = tempResultEmployee.getAvatar();
                }
            }
            indexMsgBO.setName(resultFromName);
            indexMsgBO.setAvatar(resultFromAvatar);
            respList.add(indexMsgBO);
        }
        int size = (int) page.getSize();
        int pages = total / size;
        if (total % size > 0) {
            pages++;
        }
        page.setRecords(respList);
        page.setTotal(total);
        page.setPages(pages);
        return R.ok(page);
    }

    public R<Page> getContactList(ReqMsgIndexDTO req, Page page) {
        int corpId = CorpContextHolder.getCorpId();
        List<IndexMsgBO> respList = new ArrayList<>();
        int total = 0;
        Integer userType = req.getUserType();
        WorkContactEntity fromContact = workContactMapper.selectById(req.getUserId());
        if (null == fromContact) {
            return R.ok(page);
        }
        String fromWxId = fromContact.getWxExternalUserid();
        String fromName = fromContact.getName();
        String fromAvatar = fromContact.getAvatar();

        String toWxId = "";
        int toUserType = req.getToUserType();
        if (toUserType == 0) {
            WorkEmployeeEntity employeeEntity = workEmployeeMapper.selectById(req.getToUserId());
            if (null == employeeEntity) {
                throw new CheckedException("检索对象id 无效");
            }
            toWxId = employeeEntity.getWxUserId();
        }
        if (toUserType == 2) {
            WorkRoomEntity roomEntity = workRoomMapper.selectById(req.getToUserId());
            if (null == roomEntity) {
                throw new CheckedException("检索对象id 无效");
            }
            toWxId = roomEntity.getWxChatId();
        }
        Map<String, Object> selectParamMap = new HashMap<>(9);
        //selectParamMap.put("corpId", corpId);
        selectParamMap.put("from", fromWxId);
        selectParamMap.put("msgType", req.getType());
        selectParamMap.put("to", toWxId);
        selectParamMap.put("toUserType", toUserType);
        selectParamMap.put("content", req.getContent());
        if (StringUtils.isNotEmpty(req.getDateTimeEnd()) && StringUtils.isNotEmpty(req.getDateTimeStart())) {
            try {
                selectParamMap.put("dateTimeStart", simpleDateFormat.parse(req.getDateTimeStart() + " 00:00:00").getTime());
                selectParamMap.put("dateTimeEnd", simpleDateFormat.parse(req.getDateTimeEnd() + " 23:59:59").getTime());
            } catch (ParseException e) {
                throw new IllegalArgumentException(e);
            }
        }
        selectParamMap.put("lastIndex", page.getCurrent() * page.getSize() - 1);
        selectParamMap.put("size", page.getSize());

        List<WorkMsgEntity> resultList = workMsgMapper.selectToUserMsg(selectParamMap);
        total = workMsgMapper.selectToUserMsgCount(selectParamMap);

        WorkEmployeeEntity tempEmployee = new WorkEmployeeEntity();
        WorkContactEntity tempContact = new WorkContactEntity();

        Map<String,Object> cacheMap = new HashMap<>();
        for (int i = 0; i < resultList.size(); i++) {
            WorkMsgEntity result = resultList.get(i);
            IndexMsgBO indexMsgBO = new IndexMsgBO();

            String resultFromWxId = result.getFrom();
            int isCurrentUser = fromWxId.equals(resultFromWxId) ? 1 : 0;

            indexMsgBO.setIsCurrentUser(isCurrentUser);
            indexMsgBO.setAction(MsgEnum.getEnum(result.getAction()));
            indexMsgBO.setToListType(result.getTolistType());

            int typeCode = result.getMsgType();
            typeCode = typeCode > 14 ? 100 : typeCode;

            indexMsgBO.setType(typeCode);
            indexMsgBO.setContent(JSON.parseObject(result.getContent()));

            String msgTime = result.getMsgTime();
            indexMsgBO.setMsgDataTime(DateUtils.formatS1(msgTime));

            String resultFromName;
            String resultFromAvatar;
            if (isCurrentUser == 1) {
                resultFromName = fromName;
                resultFromAvatar = fromAvatar;
            } else {
                if (WorkMsgBackUpUtil.isContact(resultFromWxId)) {
                    tempContact.setWxExternalUserid(resultFromWxId);
                    WorkContactEntity tempResultContact;
                    if (cacheMap.get(resultFromWxId) != null) {
                        tempResultContact = (WorkContactEntity) cacheMap.get(resultFromWxId);
                    } else {
                        tempResultContact = workContactMapper.selectOne(Wrappers.<WorkContactEntity>lambdaQuery()
                                .eq(WorkContactEntity::getWxExternalUserid, resultFromWxId));
                        cacheMap.put(resultFromWxId, tempResultContact);
                    }
                    resultFromName = tempResultContact.getName();
                    resultFromAvatar = tempResultContact.getAvatar();
                } else {
                    tempEmployee.setWxUserId(resultFromWxId);
                    WorkEmployeeEntity tempResultEmployee;
                    if (cacheMap.get(resultFromWxId) != null) {
                        tempResultEmployee = (WorkEmployeeEntity) cacheMap.get(resultFromWxId);
                    } else {
                        tempResultEmployee = workEmployeeMapper.selectOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                                .eq(WorkEmployeeEntity::getWxUserId, resultFromWxId));
                        cacheMap.put(resultFromWxId, tempResultEmployee);
                    }
                    resultFromName = tempResultEmployee.getName();
                    resultFromAvatar = tempResultEmployee.getAvatar();
                }
            }

            indexMsgBO.setName(resultFromName);
            indexMsgBO.setAvatar(resultFromAvatar);
            respList.add(indexMsgBO);
        }
        int size = (int) page.getSize();
        int pages = total / size;
        if (total % size > 0) {
            pages++;
        }
        page.setRecords(respList);
        page.setTotal(total);
        page.setPages(pages);
        return R.ok(page);
    }
}
